﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Interactivity;

namespace Odyssey.Behaviors
{
    /// <summary>
    /// Behavior to reformat the text of a TextBlock when loaded by analyzing the text property and replace the text with some Run elements.
    /// </summary>
    public class TextBlockFormatBehavior : Behavior<TextBlock>
    {
        protected override void OnAttached()
        {
            ParseText(AssociatedObject);
            base.OnAttached();
        }

        void OnLoaded(object sender, RoutedEventArgs e)
        {
            AssociatedObject.Loaded -= OnLoaded;
            ParseText(AssociatedObject);
        }


        public static void ParseText(TextBlock textBlock)
        {
            string[] parts = textBlock.Text.Split('*');           
            textBlock.Inlines.Clear();
            foreach (string p in parts)
            {
                if (p.Length < 1) continue;
                char cmd = p[0];
                if (cmd == 'n')
                {
                    textBlock.Inlines.Add(new LineBreak());
                    if (p.Length > 1)
                    {
                        textBlock.Inlines.Add(new Run { Text = p.Substring(1) });
                    }
                }
                else
                {
                    Run r = new Run { Text = p.Substring(1) };
                    switch (cmd)
                    {
                        case 'A':
                            r.FontSize = 26d;
                            r.FontWeight = FontWeights.Bold;
                            r.Foreground = Application.Current.Resources["PhoneAccentBrush"] as Brush;
                            break;

                        case '0':
                            r.FontStyle = FontStyles.Normal;
                            break;


                        case 'h':
                            r.FontSize = 26d;
                            r.FontWeight = FontWeights.Bold;
                            break;

                        case 'a':
                            r.Foreground = Application.Current.Resources["PhoneAccentBrush"] as Brush;
                            break;

                        case 'i':
                            r.FontStyle = FontStyles.Italic;
                            break;

                        case 'b':
                            r.FontWeight = FontWeights.Bold;
                            break;
                    }
                    textBlock.Inlines.Add(r);
                }
            }
        }

    }
}
